package com.abigdreamer.im.server.module.socketHandler;

import java.util.Map;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.abigdreamer.im.message.BaseMessage;
import com.abigdreamer.im.message.LoginMessage;
import com.abigdreamer.im.message.MessageType;
import com.abigdreamer.im.message.SysMessage;
import com.abigdreamer.im.server.log.EIMLogger;
import com.abigdreamer.im.server.module.ServerCache;
import com.abigdreamer.im.server.module.UserConnect;
import com.abigdreamer.im.server.module.msgProcessControl.MessageProcessManager;

public class ChatSocketHandler extends IoHandlerAdapter {

	public void messageReceived(IoSession session, Object message) throws Exception {

		if (message instanceof BaseMessage) {
			BaseMessage baseMessage = (BaseMessage) message;
			EIMLogger.INFO("服务器收到的消息为：" + baseMessage);
			if (baseMessage.getMsgType() == MessageType.LoginMessage_Type) {
				LoginMessage loginMessage = (LoginMessage) baseMessage;
				UserConnect userConnect = new UserConnect();
				userConnect.setTextTempSession(session);
				// 绝对为一loginMessage.getOwerQQ()+session.hashCode()
				loginMessage.setLoginID(loginMessage.getOwerQQ() + session.hashCode());

				ServerCache cache = ServerCache.getInstance();
				cache.getAllUserMap();
				// 登陆时把loginMessage的loginID作为根据放入到cache中，不能用owerQQ可能重复登陆
				cache.addUserConnect(loginMessage.getLoginID(), userConnect);
				userConnect.getTextTempSession().setAttribute("owerQQ", baseMessage.getSrcQQ());
				userConnect.getTextTempSession().setAttribute("sessionID", session.hashCode());
				MessageProcessManager.processMessage(loginMessage);
				return;
			}
			MessageProcessManager.processMessage(baseMessage);
		} else {
			EIMLogger.INFO("服务器收到非本协议的消息为");
		}

	}

	public void sessionClosed(IoSession session) throws Exception {
		String owerQQ = (String) session.getAttribute("owerQQ");
		SysMessage message = new SysMessage(owerQQ);
		message.setMsgContentType(MessageType.SysMessage_Exit);
		ServerCache cache = ServerCache.getInstance();
		Map<String, UserConnect> userConnectMap = cache.getUserConnectMap();
		for (String key : userConnectMap.keySet()) {
			UserConnect userConnect = userConnectMap.get(key);
			String destQQ = userConnect.getOwerQQ();
			message.setDestQQ(destQQ);
			userConnect.sendTextMessage(message);
		}
		userConnectMap.remove(owerQQ);
		cache.getOnLineUserMap().remove(owerQQ);
		cache.getAllUserMap().get(owerQQ).setOnline(false);
		EIMLogger.INFO("一个用户断开连接了！");
	}

	public void sessionOpened(IoSession session) throws Exception {
		super.sessionOpened(session);
		EIMLogger.INFO("一个用户打开了连接！");
	}

}
